const express = require('express');
const app = express();
const path = require('path');
//移入mysql
const mysql = require('mysql');
app.listen(3000, () => { console.log('服务器已开启') });

//配置mysql链接信息
let con = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'demo01',
})

//链接mysql
con.connect();

//post接参
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

//注册
app.post('/register', (req, res) => {
    //用户的数据
    let { username, password } = req.body;
    console.log(username, password);

    function fn1() {
        return new Promise((resolve, reject) => {
            //数据库里的内容 , 判断 用户输入的数据是否和表里的一致
            let sql = `SELECT * FROM aemo1 WHERE username = '${username}'`;

            con.query(sql, (err, result) => {
                console.log(err, result);
                //判断是否有错误信息,如果有结束
                if (err) {
                    res.send({ code: 404, msg: err });
                    return;
                }

                //判断用户名是否存在
                if (result.length > 0) {
                    res.send({ code: 400, msg: '用户名已存在' });
                    return;
                }
                resolve({ username, password });
            })
        })
    }

    async function fn2() {
        //如果不存在就添加到sql表里面
        let { username, password } = await fn1();
        let sql = `INSERT INTO aemo1 (username,password) VALUES ('${username}','${password}')`;
        con.query(sql, (err, result) => {
            //判断err是否有错，如果有提示错误信息，并结束下面操作
            if (err) {
                res.send({ code: 400, msg: err });
                return;
            }
            console.log(result);
            //判断是否有添加到sql表里
            if (result.insertId > 0) {
                res.send({ code: 200, msg: '注册成功' })
            } else {
                res.send({ code: 400, msg: '注册失败' })
            }
        })
    }
    fn2();
})

//登录
app.post('/login', (req, res) => {
    //用户的数据
    let { username, password } = req.body;
    console.log(username, password);

    //登录逻辑
    //数据库里的内容 , 判断 用户输入的数据是否和表里的一致
    let sql = `SELECT * FROM aemo1 WHERE username = '${username}' AND password = '${password}'`;
    con.query(sql, (err, result) => {
        console.log(err, result);
        //判断是否有错误信息,如果有结束
        if (err) {
            res.send({ code: 404, msg: err });
            return;
        }
        console.log(result);
        //判断用户名是否存在
        if (result.length > 0) {
            res.send({ code: 200, msg: '登录成功' });
        } else {
            res.send({ code: 400, msg: '登录失败' });

        }
    })
})